<?php

namespace App\Console\Commands\Command;

use App\Models\Train\Stations\Repositories\Interfaces\StationRepositoryInterface;
use Exception;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Facades\Excel;

class UpdateTrainStationTranslationBy
{
    /**
     * @throws BindingResolutionException
     * @throws Exception
     */
    public static function byExcel(): void
    {
        $excel = storage_path('translation/train_station.xlsx');
        if (!file_exists($excel)) {
            throw new Exception('翻译文件不存在');
        }
        $collection = new Collection();
        $data       = Excel::toArray($collection, $excel);

        $sheetData = $data[0];
        array_shift($sheetData);
        $stationRepo = app(StationRepositoryInterface::class);
        foreach ($sheetData as $key => $item) {
            $code    = $item[1];
            $station = $stationRepo->findOneByCode($code);
            // 如果存在先跳过
            if ($station?->getStationNameUy()) {
                continue;
            }
            if (!$station) {
                if (empty($item[5])) {
                    echo "新增站点更新站点翻译  不存在 {$key} --{$code}\n";
                }
                $stationRepo->addStation([
                    'station_name'    => $item[0],
                    'station_name_uy' => $item[5],
                    'station_code'    => $item[1],
                    'pinyin'          => $item[2],
                    'abbr'            => $item[3],
                    'initial'         => $item[4],
                    'initial_uy'      => $item[6],
                ]);
            } else {
                if (empty($item[5])) {
                    echo "更新站点翻译 不存在 {$key} --{$code}\n";
                }
                $res = $stationRepo->updateStation($station, [
                    'station_name'    => $item[0],
                    'station_name_uy' => $item[5],
                    'pinyin'          => $item[2],
                    'abbr'            => $item[3],
                    'initial'         => $item[4],
                    'initial_uy'      => $item[6],
                ]);
                echo "更新站点翻译    {$key} --{$code} -{$res}\n";
            }
        }

    }
}